//
//  MAShareView.m
//  TritonSDKDemo
//
//  Created by lkbfeng on 2020/8/17.
//  Copyright © 2020 Tencent Inc. All rights reserved.
//

#import "MAShareView.h"

static CGFloat const kCancelButtonHeight = 56.0;
static CGFloat const kScrollViewHeight = 106.0;
static CGFloat const kTopViewHeight = 48.0;
static CGFloat const kPadding = 12.0;
static CGFloat const kItemWidth = 60.0;
static CGFloat const kItemHeight = kScrollViewHeight;

@interface MAShareItemView : UIView

@property (nonatomic, copy) void (^tapAction)(void);

- (instancetype)initWithActivity:(MAShareActivity *)activity;

@end

@implementation MAShareItemView

- (instancetype)initWithActivity:(MAShareActivity *)activity {
    if (self = [super init]) {
        [self createUI:activity];
        [self addTapGesture];
    }
    
    return self;
}

- (void)createUI:(MAShareActivity *)activity {
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kItemWidth, kItemWidth)];
    imageView.image = activity.icon;
    [self addSubview:imageView];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(-2, CGRectGetMaxY(imageView.frame) + 6, kItemWidth + 2*2, 14)];
    label.text = activity.title;
    label.lineBreakMode = NSLineBreakByTruncatingTail;
    label.textAlignment = NSTextAlignmentCenter;
    label.font = [UIFont systemFontOfSize:10];
    label.textColor = [UIColor colorWithRed:135.0 / 255 green:139.0 / 255 blue:153.0 / 255 alpha:1.0];
    [self addSubview:label];
}

- (void)addTapGesture {
    UITapGestureRecognizer *tap = [UITapGestureRecognizer new];
    [tap addTarget:self action:@selector(tap)];
    [self addGestureRecognizer:tap];
}

- (void)tap {
    self.tapAction ? self.tapAction() : nil;
}

@end

@interface MAShareViewController : UIViewController

@property (nonatomic, assign) BOOL autoRotate;

@end

@implementation MAShareViewController

- (BOOL)shouldAutorotate {
    return self.autoRotate;
}

@end

@implementation MAShareActivity

@end

@interface MAShareView()

@property (nonatomic, strong) UIWindow *window;
@property (nonatomic, strong) UIView *sheetView;

@end

@implementation MAShareView

- (void)showInView:(UIView *)view {
    self.frame = [[UIScreen mainScreen] bounds];
    self.backgroundColor = [UIColor colorWithWhite:0 alpha:0.6];
    
    MAShareViewController *shareVC = [MAShareViewController new];
    shareVC.autoRotate = self.autoRotate;
    [shareVC.view addSubview:self];
    
    self.window = [[UIWindow alloc] initWithFrame:self.frame];
    self.window.backgroundColor = [UIColor clearColor];
    self.window.windowLevel = UIWindowLevelAlert - 1;
    self.window.hidden = NO;
    self.window.rootViewController = shareVC;
    if (@available(iOS 13.0, *)) {
        self.window.windowScene = view.window.windowScene;
    }
    
    [self addTouchGesture];
    self.needBlurEffect ? [self addBlurView] : nil;
    [self render];
    [self animateToShow];
}

- (void)addTouchGesture {
    UITapGestureRecognizer *tap = [UITapGestureRecognizer new];
    [tap addTarget:self action:@selector(dismiss)];
    [self addGestureRecognizer:tap];
}

- (void)addBlurView {
    UIToolbar *blurView = [[UIToolbar alloc] initWithFrame:self.bounds];
    blurView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    blurView.userInteractionEnabled = NO;
    blurView.barStyle = UIBarStyleBlack;
    [self addSubview:blurView];
}

- (void)render {
    self.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    
    CGFloat totalHeight = kTopViewHeight + kScrollViewHeight + kCancelButtonHeight + [self bottomSafeMargin];
    self.sheetView = [[UIView alloc] initWithFrame:CGRectMake(0,
                                                              self.bounds.size.height - totalHeight,
                                                              self.bounds.size.width,
                                                              totalHeight)];
    self.sheetView.backgroundColor = [UIColor colorWithRed:243.0 / 255 green:244.0 / 255 blue:248.0 / 255 alpha:1.0];
    self.sheetView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
    [self addSubview:self.sheetView];
    
    UIButton *topButton = [[UIButton alloc] initWithFrame:CGRectMake(0,
                                                                     0,
                                                                     self.bounds.size.width,
                                                                     kTopViewHeight)];
    topButton.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    [topButton setTitle:@"分享到" forState:UIControlStateNormal];
    [topButton setTitleColor:[UIColor colorWithRed:135.0 / 255 green:139.0 / 255 blue:153.0 / 255 alpha:1.0] forState:UIControlStateNormal];
    [topButton.titleLabel setFont:[UIFont systemFontOfSize:12]];
    [self.sheetView addSubview:topButton];
    
    UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0,
                                                                              CGRectGetMaxY(topButton.frame),
                                                                              self.bounds.size.width,
                                                                              kScrollViewHeight)];
    scrollView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    scrollView.clipsToBounds = YES;
    scrollView.showsHorizontalScrollIndicator = NO;
    [self updateScrollView:scrollView];
    [self.sheetView addSubview:scrollView];
    
    UIButton *cancelButton = [[UIButton alloc] initWithFrame:CGRectMake(0,
                                                                        CGRectGetMaxY(scrollView.frame),
                                                                        self.bounds.size.width,
                                                                        kCancelButtonHeight)];
    cancelButton.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    cancelButton.backgroundColor = [UIColor whiteColor];
    [cancelButton addTarget:self action:@selector(cancel:) forControlEvents:UIControlEventTouchUpInside];
    [cancelButton setTitle:@"取消" forState:UIControlStateNormal];
    [cancelButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [cancelButton.titleLabel setFont:[UIFont boldSystemFontOfSize:17]];
    [self.sheetView addSubview:cancelButton];
}

- (void)updateScrollView:(UIScrollView *)scrollView {
    CGFloat originY = kPadding;
    for (MAShareActivity *activity in self.activityItems) {
        MAShareItemView *view = [[MAShareItemView alloc] initWithActivity:activity];
        
        __weak typeof(self) weakSelf = self;
        view.tapAction = ^{
            __strong typeof(weakSelf) self = weakSelf;
            [self dismissWithAnimated:YES];
            activity.actionBlock ? activity.actionBlock() : nil;
        };
        view.frame = CGRectMake(originY, 0, kItemWidth, kItemHeight);
        [scrollView addSubview:view];
        originY += kPadding + kItemWidth;
    }
    scrollView.contentSize = CGSizeMake(originY, scrollView.frame.size.height);
}

- (void)animateToShow {
    CGRect normalFrame = self.sheetView.frame;
    self.sheetView.frame = CGRectMake(0, self.bounds.size.height, normalFrame.size.width, normalFrame.size.height);
    self.alpha = 0;
    
    [UIView animateWithDuration:0.5
                          delay:0
         usingSpringWithDamping:0.7
          initialSpringVelocity:0
                        options:UIViewAnimationOptionCurveEaseInOut
                     animations:^{
        self.sheetView.frame = normalFrame;
        self.alpha = 1;
    }
                     completion:NULL];
}

- (void)cancel:(id)sender {
    self.cancelActionBlock ? self.cancelActionBlock() : nil;
    [self dismiss];
}

- (void)dismiss {
    [self dismissWithAnimated:YES];
}

- (void)dismissWithAnimated:(BOOL)animated {
    if (!animated) {
        self.dismissBlock ? self.dismissBlock() : nil;
        self.window.hidden = YES;
        self.window = nil;
        return;
    }
    
    [UIView animateWithDuration:0.25
                     animations:^{
        self.alpha = 0;
    }
                     completion:^(BOOL finished) {
        self.window.hidden = YES;
        self.window = nil;
        self.dismissBlock ? self.dismissBlock() : nil;
    }];
}

- (CGFloat)bottomSafeMargin {
    CGFloat homeBarHeight = 0;
    if (@available(iOS 11.0, *)) {
        homeBarHeight = self.window.safeAreaInsets.bottom;
    }
    return homeBarHeight;
}

@end
